/**
 * 
 */
package org.oproject.framework.orm.ibatis;

import java.sql.SQLException;
import java.util.Collection;

import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.SqlMapClientTemplate;

import com.ibatis.sqlmap.client.SqlMapExecutor;

/**
 * <p><strong>基于Spring的SqlMapClientTemplate对象</strong></p>
 * <p></p>
 * @see
 * @version v1.0
 * @since v2.0
 * @author ahli (edit in 2010-6-14)
 */
public class BatchExecuteUtils {

	/**
	 * 单态
	 */
	private final static BatchExecuteUtils instance = new BatchExecuteUtils();
	
	/**
	 * 私有构造函数
	 */
	private BatchExecuteUtils(){}

	/**
	 * 获取QueryUtils实例
	 * @return    QueryUtils实例
	 */
	public static BatchExecuteUtils getInstance(){
		return instance;
	}
	
	/**
	 * 批量保存
	 * @param sqlMapClientTemplate
	 * @param stmt
	 * @param col
	 */
	@SuppressWarnings("unchecked")
	public void batchInsert(SqlMapClientTemplate sqlMapClientTemplate, final  String stmt, final Collection<? extends Object> col){
		sqlMapClientTemplate.execute(new SqlMapClientCallback()
		{
			public Object doInSqlMapClient(SqlMapExecutor executor)
					throws SQLException
			{
				executor.startBatch();
				for(Object obj : col){
					executor.insert(stmt, obj);
				}
				return executor.executeBatch();
			}
		});
	}
	
	@SuppressWarnings("unchecked")
	public void batchUpdate(SqlMapClientTemplate sqlMapClientTemplate, final String stmt, final Collection<? extends Object> col){
		sqlMapClientTemplate.execute(new SqlMapClientCallback()
		{
			public Object doInSqlMapClient(SqlMapExecutor executor)
					throws SQLException
			{
				executor.startBatch();
				for(Object obj : col){
					executor.update(stmt, obj);
				}
				return executor.executeBatch();
			}
		});
	}
	
	@SuppressWarnings("unchecked")
	public void batchDelete(SqlMapClientTemplate sqlMapClientTemplate, final String stmt, final Collection<? extends Object> col){
		sqlMapClientTemplate.execute(new SqlMapClientCallback()
		{
			public Object doInSqlMapClient(SqlMapExecutor executor)
					throws SQLException
			{
				executor.startBatch();
				for(Object obj : col){
					executor.delete(stmt, obj);
				}
				return executor.executeBatch();
			}
		});
	}
	
}
